#include <iostream>
#include "sqlite3recover.h"


/*
** This function is called to recover data from the database.
*/
static int recoverDatabase(sqlite3 *db){
  int rc;                                 /* Return code from this routine */
  const char *zLAF = "lost_and_found";    /* Name of "lost_and_found" table */
  int bFreelist = 1;                      /* True to scan the freelist */
  int bRowids = 1;                        /* True to restore ROWID values */
  sqlite3_recover *p;                     /* The recovery object */

  const char *out_db = "/home/kylin/prj/gitee/sqlite-db-recover/sqlite-db-recover/111/111/recovered.db"; // 指定输出路径
  p = sqlite3_recover_init(db, "main", out_db);

  sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
  sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
  sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
  sqlite3_recover_run(p);
  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
    const char *zErr = sqlite3_recover_errmsg(p);
    int errCode = sqlite3_recover_errcode(p);
      printf("recovery error: %s (%d)\n", zErr, errCode);
  }
  rc = sqlite3_recover_finish(p);
  if(rc){
     printf("recovery returns error code %d\n", rc);
  }
  return rc;
}

int main(int argc, char **argv){ 

    sqlite3 *db;  // 数据库句柄
    const char *db_path = "/home/kylin/prj/gitee/sqlite-db-recover/sqlite-db-recover/111/111/fileinfo.db";  // 损坏的数据库文件路径

    // 1. 先尝试打开数据库（即使可能损坏）
    int rc = sqlite3_open(db_path, &db);
    if (rc != SQLITE_OK) {
        printf("打开数据库失败（可能已损坏），但仍可尝试恢复\n");
        // 即使打开失败，某些恢复操作仍可能进行
    }

    // 2. 调用恢复函数
    rc = recoverDatabase(db);
    if (rc == SQLITE_OK) {
        printf("恢复成功！\n");
    } else {
        printf("恢复失败，错误码: %d\n", rc);
    }

    // 3. 关闭数据库
    sqlite3_close(db);
}